package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.Question;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

/**
 * @Author YuShiLong
 * @Date 2021/4/14 20:06
 * @Version 1.0
 */
@Service
public class TodayBestService {

    @Autowired
    private UserService userService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    @Autowired
    private QuestionService questionService;

    @Value("${tanhua.sso.url}")
    private String url;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RestTemplate restTemplate;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Reference(version = "1.0.0")
    private SoundApi soundApi;

    public TodayBest queryTodayBest() {

        //校验token是否有效，通过sso接口进行校验
        User user = UserThreadLocal.get();

        //查询今日佳人，调用dubbo中提供的方法
        TodayBest todayBest = recommendUserService.queryTodayBest(user.getId());
        if (todayBest == null) {
            //给出默认推荐
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            //固定缘分值
            todayBest.setFateValue(80L);
        }

        //通过推荐的userId获取对应的UserInfo，然后补全今日佳人的个人信息
        UserInfo userInfo = userInfoService.queryUserByUserId(todayBest.getId());

        if (userInfo == null) {
            return null;
        }

        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setAge(userInfo.getAge());

        return todayBest;
    }


    public PageResult queryRecommendation(RecommendUserQueryParam queryParam) {
        //校验token是否有效，通过sso接口进行校验
        User user = UserThreadLocal.get();

        //new一个PageResult，用于作为返回值
        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());

        //调用dubbo中提供的queryRecommendUserList方法，查询推荐用户列表(获取的信息是有哪些推荐用户，信息不全，在下面补全)
        //获取的推荐列表可以为空
        PageInfo<RecommendUser> pageInfo = recommendUserService.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPagesize());

        //获取查询出来的用户列表
        List<RecommendUser> records = pageInfo.getRecords();


        //判断查询出来的数据是否为空
        if (CollectionUtils.isEmpty(records)) {
            //没有查询到推荐的用户列表，如果为空返回一个默认的列表
            String[] ss = StringUtils.split(defaultRecommendUsers, ',');
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();

                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                recommendUser.setScore(RandomUtils.nextDouble(70, 99));

                records.add(recommendUser);
            }
        }

        //填充个人信息

        //获取推荐用户的id
        Set<Long> userIds = new HashSet<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }

        //构建查询条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

        //设置用户id
        queryWrapper.in("user_id", userIds);

       /* //传入的性别不为空
        if (StringUtils.isNotEmpty(queryParam.getGender())) {
            //需要性别参数的查询
            queryWrapper.eq("sex", StringUtils.equals(queryParam.getGender(), "man") ? 1 : 2);
        }

        //传入的城市不为空
        if (StringUtils.isNotEmpty(queryParam.getCity())) {
            //需要城市参数查询
            queryWrapper.like("city", queryParam.getCity());
        }

        //年龄小于等于
        if (queryParam.getAge() != null) {
            //设置年龄参数
            queryWrapper.le("age",queryParam.getAge());
        }*/

        //查询推荐用户的完整信息
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);

        //判断返回的结果
        if (CollectionUtils.isEmpty(userInfoList)) {
            //没有查询到用户的基本信息
            return pageResult;
        }

        //定义一个集合，用来接收获取的推荐用户信息
        List<TodayBest> todayBests = new ArrayList<>();

        //查询到用户信息
        for (UserInfo userInfo : userInfoList) {
            //获取推荐用户，并填充数据
            TodayBest todayBest = new TodayBest();

            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setAge(userInfo.getAge());

            //设置缘分值,缘分值在records里面需要再次遍历
            for (RecommendUser record : records) {
                if (record.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    double score = Math.floor(record.getScore());//取整,98.2 -> 98
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }

            todayBests.add(todayBest);

        }

        //按照缘分值进行倒序排序
        Collections.sort(todayBests, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());

        //将推荐用户集合装入pageResult，来返回数据
        pageResult.setItems(todayBests);

        return pageResult;
    }

    public TodayBest queryTodayBest(Long userId) {

        User user = UserThreadLocal.get();

        TodayBest todayBest = new TodayBest();
        //补全信息
        UserInfo userInfo = this.userInfoService.queryUserByUserId(userId);
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        double score = this.recommendUserService.queryScore(userId, user.getId());
        if (score == 0) {
            score = 98; //默认分值
        }

        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }

    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (null != question) {
            return question.getTxt();
        }
        return "";
    }

    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserByUserId(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", this.queryQuestion(userId));
        msg.put("strangerQuestion", userInfo.getNickName());
        msg.put("reply", reply);

        try {
            String msgStr = MAPPER.writeValueAsString(msg);

            String targetUrl = this.url + "/user/huanxin/messages";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }

    public List<NearUserVo> queryNearUser(String gender, String distance) {

        User user = UserThreadLocal.get();
        //查询当前用户的地理位置
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(user.getId());

        Double longitude = userLocationVo.getLongitude();
        Double latitude = userLocationVo.getLatitude();

        //查询附件的好友
        List<UserLocationVo> userLocationVoList = userLocationApi.queryUserFromLocation(longitude, latitude, Integer.valueOf(distance));
        if (CollectionUtils.isEmpty(userLocationVoList)) {
            return Collections.emptyList();
        }

        //获取用户的idLIst,并且配合性别进行条件搜索
        List<Long> userIds = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            userIds.add(locationVo.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.eq("sex", SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.eq("sex", SexEnum.WOMAN);
        }

        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            if (userInfo.getUserId().longValue() == user.getId().longValue()) {
                // 排除自己
                continue;
            }
            NearUserVo nearUserVo = new NearUserVo();

            nearUserVo.setUserId(userInfo.getUserId());
            nearUserVo.setAvatar(userInfo.getLogo());
            nearUserVo.setNickname(userInfo.getNickName());
            nearUserVoList.add(nearUserVo);
        }

        //最后返回数据
        return nearUserVoList;
    }

    public List<TodayBest> queryCardsList() {

        User user = UserThreadLocal.get();
        int count = 50;

        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), 1, count);
        List<RecommendUser> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            //默认推荐列表
            String[] ss = StringUtils.split(defaultRecommendUsers, ',');
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                records.add(recommendUser);
            }
        }

        //取10和records.size()中的最小值
        int showCount = Math.min(10, records.size());

        //洗牌，最多。list.size()次
        Collections.shuffle(records);

        List<RecommendUser> newRecommendUserList = records.subList(0, showCount);

        //获取用户id,封装进userIds集合
        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : newRecommendUserList) {
            userIds.add(record.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setFateValue(0L);

            todayBests.add(todayBest);
        }

        return todayBests;
    }

    public boolean likeUser(Long likeUserId) {

        User user = UserThreadLocal.get();
        String id = this.userLikeApi.saveUserLike(user.getId(), likeUserId);
        if (StringUtils.isEmpty(id)) {
            return false;
        }

        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUsers(likeUserId);
        }
        return true;

    }

    public Boolean disLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId(), likeUserId);
    }

    public Boolean sendVoice(MultipartFile soundFile) {

        //获取user对象
        User user = UserThreadLocal.get();

        //将语音保存到redis中,语音只能发送十次
        //设置当前时间
        Date date = new Date();
        //设置时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);

        //设置存入redis中的key
        String redisKey = user.getId() + "_" + dateTime + "_SEND_SOUND";

        //判断redis中当前key存在的次数
        String value = redisTemplate.opsForValue().get(redisKey);
        if (null == value) {
            //说明当前redis中没有存入数据,则将数据存入redis,并设置次数为9
            redisTemplate.opsForValue().set(redisKey, "9", Duration.ofDays(1));
        } else if (value.equals("0")) {
            //说明当前发送语音的次数已经用完
            return false;
        } else {
            //其他的情况为,将数据存入redis,并将次数减一
            redisTemplate.opsForValue().decrement(redisKey);
        }

        //定义一个Sound,然后更加userId获取user的信息,然后填充进Sound里面
        UserInfo u = userInfoService.queryUserByUserId(user.getId());
        Sound sound = new Sound();
        sound.setUserId(user.getId());
        sound.setGender(u.getSex().name());

        try {
            //将语音上传到fastdfs上
            //上传图片到FastDFS
            StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(),
                    soundFile.getSize(),
                    StringUtils.substringAfter(soundFile.getOriginalFilename(), "."),
                    null);
            sound.setSoundUrl(fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath());
            //sound.setSoundUrl(upload.getName());
            this.soundApi.saveSound(sound);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public SoundVo querySound() {
        //获取当前的user对象
        User user = UserThreadLocal.get();

        //判断该用户当天接收语音的次数,每天只能接收十次
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = simpleDateFormat.format(date);
        //记当天的接收次数
        String redisKey = user.getId() + "_" + dateTime + "_GET_SOUND";

        //查询redis,判断redis中当前key存在的次数
        String value = redisTemplate.opsForValue().get(redisKey);
        if (null == value) {
            //说明当前redis中没有存入数据,则将数据存入redis,并设置次数为9
            redisTemplate.opsForValue().set(redisKey, "9", Duration.ofDays(1));
        } else if (value.equals("0")) {
            //说明当前发送语音的次数已经用完
            return null;
        } else {
            //其他的情况为,将数据存入redis,并将次数减一
            redisTemplate.opsForValue().decrement(redisKey);
        }

        //获取语音集合,获取排除本人id的语音
        List<Sound> sounds = soundApi.querySounds(user.getId());
        if (CollectionUtils.isEmpty(sounds)) {
            return null;
        }

        Collections.shuffle(sounds);

        Sound s = sounds.get(0);
        Long userId = s.getUserId();

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserInfo result = userInfoService.queryUserByUserId(userId);

        SoundVo soundVo = new SoundVo();
        soundVo.setUserId(result.getId());
        soundVo.setAge(result.getAge());
        soundVo.setAvatar(result.getLogo());
        soundVo.setNickname(result.getNickName());
        soundVo.setGender(result.getSex().getValue() == 1 ? "man" : "woman");
        soundVo.setAge(result.getAge());
        soundVo.setSoundUrl(s.getSoundUrl());
        int count = Integer.parseInt(redisTemplate.opsForValue().get(redisKey));
        soundVo.setRemainingTimes(count);

        return soundVo;

    }
}
